﻿using System;
using System.Windows.Controls;

namespace CommonUtils
{
    public static class ControlCache
    {
        public static void SaveValue(this TextBox textBox)
        => CacheUtil.SaveWithFile(textBox.Name, textBox.Text); //这里不加空判断，有时候要的就是空值

        /*
        * 此处赋值textBox.Text = text
        * 如果textBox.Text == text 不会触发TextChanged
        * 如果textBox.Text != text 会触发TextChanged
        * 但是textBox进行前端输入(包括粘贴,输入相同字符) 无论==、!=都会触发TextChanged
        */
        public static void SaveOnChange(this TextBox textBox)
        {
            textBox.TextChanged += delegate
            {
                ConsoleUtil.Write("TextBox({0}).Save({1})", textBox.Name, textBox.Text.AddDoubleQuotes());
                textBox.SaveValue();
            };
        }

        public static void Load(this TextBox textBox, string path = null)
        {
            ConsoleUtil.Write("TextBox({0}).LoadText()", textBox.Name);

            string text;

            if (string.IsNullOrEmpty(path))
                text = CacheUtil.GetFromFile<string>(textBox.Name);
            else
                text = FileUtil.GetText(path);

            if (!string.IsNullOrEmpty(text))
                textBox.Text = text;
        }

        public static void SaveValue(this CheckBox checkBox)
        => CacheUtil.SaveWithFile(checkBox.Name, checkBox.IsChecked.Value);

        public static void SaveValueOnChange(this CheckBox checkBox)
        => checkBox.Click += delegate { checkBox.SaveValue(); };

        public static void LoadValue(this CheckBox checkBox)
        => checkBox.IsChecked = CacheUtil.GetFromFile<bool>(checkBox.Name);

        public static void SaveValue(this Calendar calendar)
        => CacheUtil.SaveWithFile(calendar.Name, calendar.SelectedDate);

        public static void SaveValueOnChange(this Calendar calendar)
        => calendar.SelectedDatesChanged += delegate { calendar.SaveValue(); };

        public static void LoadValue(this Calendar calendar)
        => calendar.SelectedDate = CacheUtil.GetFromFile<DateTime>(calendar.Name);
    }
}
